package com.small.nacos.client.naming.net;

import com.alibaba.nacos.common.http.AbstractHttpClientFactory;
import com.alibaba.nacos.common.http.HttpClientBeanHolder;
import com.alibaba.nacos.common.http.HttpClientConfig;
import com.alibaba.nacos.common.http.HttpClientFactory;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.tls.TlsSystemConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author zhoujin
 * @Date 2022/7/21 20:41
 */
public class NamingHttpClientManager {

    private static final int READ_TIME_OUT_MILLIS = Integer
            .getInteger("com.small.nacos.client.naming.rtimeout", 50000);

    private static final boolean ENABLE_HTTPS = Boolean.getBoolean(TlsSystemConfig.TLS_ENABLE);

    private static final int CON_TIME_OUT_MILLIS = Integer.getInteger("com.small.nacos.client.naming.ctimeout", 3000);


    private static final int MAX_REDIRECTS = 5;

    private static final HttpClientFactory HTTP_CLIENT_FACTORY = new NamingHttpClientFactory();

    private static class NamingHttpClientManagerInstance {
        private static final NamingHttpClientManager INSTANCE = new NamingHttpClientManager();
    }
    public static NamingHttpClientManager getInstance() {
        return NamingHttpClientManagerInstance.INSTANCE;
    }

    public NacosRestTemplate getNacosRestTemplate() {
        return HttpClientBeanHolder.getNacosRestTemplate(HTTP_CLIENT_FACTORY);
    }

    private static class NamingHttpClientFactory extends AbstractHttpClientFactory {

        private static final Logger LOGGER = LoggerFactory.getLogger(NamingHttpClientFactory.class);

        @Override
        protected HttpClientConfig buildHttpClientConfig() {
            return HttpClientConfig.builder().setConTimeOutMillis(CON_TIME_OUT_MILLIS)
                    .setReadTimeOutMillis(READ_TIME_OUT_MILLIS).setMaxRedirects(MAX_REDIRECTS).build();
        }

        @Override
        protected Logger assignLogger() {
            return LOGGER;
        }
    }

    public String getPrefix() {
        if (ENABLE_HTTPS) {
            return "https://";
        }
        return "http://";
    }
}
